import pymysql
from src.db.sql_generations import *
import threading

class DbRunner:
    def __init__(self, host, user, pswd, database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor):
        self.db = pymysql.connect(
            host        = host,   # 数据库地址
            user        = user,  # 数据库用户名
            password    = pswd,  # 数据库密码
            database    = database,  # 数据库名
            charset     = charset,  # 字符集
            cursorclass = cursorclass  # 结果以字典形式返回
        )
        self.cursor = self.db.cursor()
        self.mutex  = threading.Lock()
    
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.db:
            self.db.close()
            print("数据库连接已关闭")

    def insert(self, table_name, columns, values):
        sql_insert = generate_insert_sql(table_name, columns)
        # print("插入数据SQL语句：", sql_insert)

        try:
            for value in values:
                self.cursor.execute(sql_insert, value)
            self.db.commit()
            # print("数据插入成功！")
        except Exception as e:
            e.args = (f"插入数据失败: {e}",)
            print(e)
            self.close()

    def delete_test_data(self, table_name, where=None):
        sql_delete = generate_delete_sql(table_name, where)
        # print("删除数据SQL语句：", sql_delete)

        try:
            self.cursor.execute(sql_delete)
            self.db.commit()
            # print("数据删除成功！")
        except Exception as e:
            e.args = (f"删除数据失败: {e}",)
            self.close()

    def select_data(self, table_name, columns='*', where=None, limit=None):
        sql_select = generate_select_sql(table_name, columns, where, limit)
        # print("查询数据SQL语句：", sql_select)

        try:
            self.cursor.execute(sql_select)
            results = self.cursor.fetchall()  # 获取所有记录
            # print("\n查询结果：")
            # for row in results:
            #     print(type(row), row)
            return results
        except Exception as e:
            e.args = (f"查询数据失败: {e}",)
            self.close()

    def update_single_column(self, table_name : str, column : str, value, where=None): 
        """更新单个列的值"""
        sql_update = f"UPDATE {table_name} SET {column} = %s WHERE {where}"
        # print("更新数据SQL语句：", sql_update)

        try:
            self.cursor.execute(sql_update, (value))
            self.db.commit()
            # print("数据更新成功！")
        except Exception as e:
            e.args = (f"更新数据失败: {e}",)
            self.close()

# runner = DbRunner('localhost', 'lml', '681020', 'helloworld')

# runner.insert_test_data('test_data', 
#                         ['object_api_name', 'data_type', 'operation_type', 'test_data'],
#                         [('object_cbb246f2bd1', Datatype.NORMAL.value, OperationType.CREATE.value, json.dumps(test_insert_data, ensure_ascii=False))])
# runner.select_data('test_data')  # 查询数据

# runner.close()        